<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>面试</title>
    <!-- IMPORT CSS -->
    <link rel="stylesheet" href="reset.min.css">
    <style>
        #box {
            width: 200px;
            height: 200px;
            background: lightblue;

            /* 设置JS动画的元素最好脱离文档流,以此降低DOM回流消耗的性能 */
            position: absolute;
            top: 0;
            left: 0;
            z-index: 999;
        }
    </style>
</head>

<body>
    <div id="box"></div>

    <!-- IMPORT JS -->
    <script>
        (function () {
            let box = document.querySelector('#box');
            let time = 0,
                timer = null;

            // 匀速运动的公式：t已经运动的时间 b起始位置 c总距离 d总时间，基于公式可以计算出当前的位置
            const linear = function linear(t, b, c, d) {
                return c * t / d + b;
            };

            // 开始运动  1000是总时间  300是总距离  起始位置0
            timer = setInterval(() => {
                time += 16;
                if (time >= 1000) {
                    // 动画结束
                    clearInterval(timer);
                    timer = null;
                    box.style.left = '300px';
                    return;
                }
                let cur = linear(time, 0, 300, 1000);
                box.style.left = `${cur}px`;
            }, 16);
        })();
    </script>
</body>

</html>